package data

import (
	"commerce/common"
	"commerce/model"
	"fmt"
)

func ListProvince() ([]model.Province, error) {

	stmt, err := common.DB.Prepare("select id, province_id, province FROM provinces")
	if err != nil {
		return nil, err
	}
	defer stmt.Close()

	rows, err := stmt.Query()
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var ps []model.Province
	for rows.Next() {
		p := model.Province{}
		if err := rows.Scan(&p.Id, &p.ProvinceId, &p.Province); err != nil {
			return nil, fmt.Errorf("省数据有误:%s", err.Error())
		}
		ps = append(ps, p)
	}
	return ps, nil
}

func ListCity(provinceId int) ([]model.City, error) {

	stmt, err := common.DB.Prepare("select id, city_id, city, province_id FROM cities where province_id = ?")
	if err != nil {
		return nil, err
	}
	defer stmt.Close()

	rows, err := stmt.Query(provinceId)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var cs []model.City
	for rows.Next() {
		c := model.City{}
		if err := rows.Scan(&c.Id, &c.CityId, &c.City, &c.ProvinceId); err != nil {
			return nil, fmt.Errorf("市数据有误:%s", err.Error())
		}
		cs = append(cs, c)
	}
	return cs, nil
}

func ListRegion(cityId int) ([]model.Area, error) {

	stmt, err := common.DB.Prepare("select id, area_id, area, city_id FROM areas where city_id = ?")
	if err != nil {
		return nil, err
	}
	defer stmt.Close()

	rows, err := stmt.Query(cityId)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var rs []model.Area
	for rows.Next() {
		r := model.Area{}
		if err := rows.Scan(&r.Id, &r.AreaId, &r.Area, &r.CityId); err != nil {
			return nil, fmt.Errorf("区数据有误:%s", err.Error())
		}
		rs = append(rs, r)
	}
	return rs, nil
}
